<template>
  <div class="about-master-container">
    <base-breadcrumb>
      <a-row :gutter="10" class="page-height">
        <a-col
          :span="6"
          class="permission-collapsed"
          :class="{ 'permission-tree-collapsed': collapsed }"
        >
          <a-card
            class="page-height-tree"
            v-loading="treeShow"
            :style="{ border: collapsed ? 'none' : 'border: 1px solid #e8e8e8' }"
          >
            <title-name title="投诉分类信息" />
            <a-input-search
              v-model="searchStr"
              placeholder="输入搜选项"
              @search="onSearch"
            />
            <!-- selectedKeys是选中项key的集合，expandedKeys是展开项key的集合 -->
            <a-tree
              v-if="treeData"
              v-model="checkedKeys"
              :tree-data="treeData"
              :selected-keys="selectedKeys"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :replace-fields="replaceFields"
              @expand="onExpand"
              @select="treeSelect"
              @onCheck="onCheck"
            >
              <template
                slot="title"
                slot-scope="{name}"
              >
                <span v-html="name.replace(new RegExp(searchValue,'g'),'<span style=color:#f50>'+ searchValue +'</span>')" />
              </template>
            </a-tree>
          </a-card>
        </a-col>
        <!-- 树搜索 -->
        <a-col
          :span="18"
          class="permission-collapsed page-height-list-wrapper"
          :style="collapsed ? 'width:calc(100% - 10px)' : ''"
        >
          <searchData
            :search-data="searchArr"
            @search="search"
          />

          <a-card :bordered="false"  class="page-height-list">
            <!-- <title-name title="投诉事项" /> -->
            <list-table
              ref="table"
              :loading="loading"
              :pagination="false"
              :columns="columns"
              :request="loadData"
              row-key="id"
            >
              <span
                slot="serial"
                slot-scope="text, record, index"
              >{{ index + 1 }}</span>
              <span
                slot="type"
                slot-scope="text, record, index"
              >
                <template>
                  <span v-if="record.type == 1">一般投诉</span>
                  <span v-else-if="record.type == 2">严重投诉</span>
                  <span v-else-if="record.type == 3">紧急投诉</span>
                </template>
              </span>

              <span
                slot="action"
                slot-scope="text, record"
              >
                <template>
                  <span v-if="hideBuquBtn()">
                    <a @click="addCustList(record)">编辑</a>
                  </span>
                </template>
              </span>
            </list-table>
          </a-card>
        </a-col>
      </a-row>

      <a-modal
        title="编辑投诉类型"
        :visible="typeShow"
        style="width: 50%;"
        @ok="handleSubmit"
        @cancel="handleClose"
      >
        <a-form-model
          ref="RuleForm"
          :model="formData"
          :rules="rules"
        >
          <a-form-model-item
            label="投诉事项"
            prop="name"
          >
            <BaseInput v-model="formData.name" />
          </a-form-model-item>
          <a-form-model-item label="投诉级别">
            <a-select
              v-model="formData.type"
              placeholder="请选择"
              disabled
            >
              <a-select-option
                v-for="item in levelData"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </base-breadcrumb>
  </div>
</template>

<script>
import UploadList from '@/components/UploadList' // 图片上传
import { getLoginsList } from '@/api/project/loginInfo'
import PermissionTreeOrganization from '@/components/businessComponents/PermissionTreeOrganization'
import { selectOption } from '@/api/material/goods/goods'
import { queryTreeList } from '@/api/partyMasses/leagueManage'
import { getCustOrgTree, getOrgsTree } from '@/api/subassembly/TreeSelectOrganization' // api
import TreeUnion from './treeUnion' // 树

import {
  getComplaintTree, queryComplaintTree, updateByPrimaryKeySelective, getPageCustomerComplaintInfo,
  getCustomerDataManagerById, addCustomerDataManager, editCustomerDataManager
} from '@/api/complaint'
const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
export default {
  name: 'a' + Date.now(),
  components: {
    TreeUnion
  },
  data () {
    return {
      loading: false,
      typeShow: false,
      collapsed: false,
      treeId: '',
      type: '',
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,

      searchValue: '',
      selectOptions: {},
      rules: {
        name: { required: true, message: '请输入投诉事项', trigger: 'blur' },
      },
      levelData: [
        {
          name: '一般投诉',
          id: '1'
        },
        {
          name: '严重投诉',
          id: '2'
        },
        {
          name: '紧急投诉',
          id: '3'
        }
      ],
      state: Number(this.$route.query.state),
      formData: {},
      tableData: [],
      columns: [
        {
          title: '序号',
          width:60,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '投诉事项',
          width:340,

          dataIndex: 'name'
        },
        {
          title: '紧急程度',
          dataIndex: 'type',
          width:140,
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '操作',
          width:100,
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        },

      ],
      tree: [],
      query: {},
        replaceFields: { title: 'name' },
      expandedKeys: [],
      backupsExpandedKeys: [],
      autoExpandParent: false,
      checkedKeys: [],
      selectedKeys: [],
      treeData: null,
      searchStr: '',
      treeShow: false,
      searchArr: [
        {
          name: '投诉事项',
          value: 'name',
          type: 'input'
        },
        {
          name: '紧急程度',
          value: 'type',
          type: 'select',
          data: [
            {
              label: '一般投诉',
              value: '1'
            },
            {
              label: '严重投诉',
              value: '2'
            },
            {
              label: '紧急投诉',
              value: '3'
            }
          ],
        },
      ],
      loadData: (parameter) => {
          let that = this
          this.loading = true;
          parameter.pageNum = parameter.pageNo;
          delete parameter.pageNo;
          const requestParameters = {param: { treeId: this.treeId, ...this.query }, ...parameter}
          return getPageCustomerComplaintInfo(requestParameters).then((res) => {
             let list = res.data?.list;
             this.loading = false;
             return { code: 200, data: list, totalSize: res.data?.total }
          })
        }, 
    }
  },
  created () {
        queryComplaintTree({name:''}).then(res=>{
               res.data[0].scopedSlots= { title: 'title' }
         res.data[0].children.forEach(item=>{
             item.scopedSlots= { title: 'title' }
             item.children.forEach(ite=>{
             ite.scopedSlots= { title: 'title' }
             })
         })
          this.treeData=res.data[0].children
      })
    this.getTree()

  },
  mounted(){
        // this.$refs.treeOrganization.getList().then((res) => {
            // this.$refs.table.refresh(true)
        // })
  },
  methods: {
    onSearch() {
      this.searchValue = this.searchStr;
      if (this.searchValue === '') {
        this.expandedKeys = [];
      } else {
        this.expandedKeys = [];
        this.backupsExpandedKeys = [];
        const candidateKeysList = this.getkeyList(this.searchValue, this.treeData, []);
        console.log(candidateKeysList,this.treeData)
        candidateKeysList.forEach(
          (item) => {
            const key = this.getParentKey(item, this.treeData);
            // eslint-disable-next-line no-shadow
            if (key && !this.backupsExpandedKeys.some((item) => item === key)) this.backupsExpandedKeys.push(key);
          },
        );
        const { length } = this.backupsExpandedKeys;
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < length; i++) {
          this.getAllParentKey(this.backupsExpandedKeys[i], this.treeData);
        }
        this.expandedKeys = this.backupsExpandedKeys.slice();
      }
      console.log(this.expandedKeys,1)
    },
    // 获取节点中含有value的所有key集合
    getkeyList(value, tree, keyList) {
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.name.indexOf(value) > -1) {
          keyList.push(node.key);
        }
        if (node.children) {
          this.getkeyList(value, node.children, keyList);
        }
      }
    //   console.log(keyList,1)
      return keyList;
    },
    // 该递归主要用于获取key的父亲节点的key值
    getParentKey(key, tree) {
      let parentKey;
      let temp;
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some((item) => item.key === key)) {
            parentKey = node.key;
            // eslint-disable-next-line no-cond-assign
          } else if (temp = this.getParentKey(key, node.children)) {
            parentKey = temp;
          }
        }
      }
      return parentKey;
    },
    // 获取该节点的所有祖先节点
    getAllParentKey(key, tree) {
      let parentKey;
      if (key) {
        parentKey = this.getParentKey(key, tree);
        if (parentKey) {
          if (!this.backupsExpandedKeys.some((item) => item === parentKey)) {
            this.backupsExpandedKeys.push(parentKey);
          }
          this.getAllParentKey(parentKey, tree);
        }
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys;
    },
    //     onSelect(e) {
    //         this.$emit('onOrgSelect', e)
    //     },
    // onExpand (expandedKeys) {
    //   this.expandedKeys = expandedKeys;
    //   this.autoExpandParent = false;
    // },
    onChange (e) {
      if (value == '') {

      }
      const value = e.target.value;
      console.log(value)
      this.tree.map(item => {
        if (item.name.indexOf(value) > -1) {
          this.tree = [item]
        } else {
          item.childrenList.map(ite => {
            if (ite.name.indexOf(value) > -1) {
              this.tree = [ite]
            } else {
              this.tree = []
            }
          })
        }
      })
      // const expandedKeys = this.tree
      //   .map(item => {
      //         // :replace-fields="{ children: 'childrenList', title: 'name', key: 'id' }"

      //     if (item.name.indexOf(value) > -1) {
      //       return getParentKey(item.id, this.tree);
      //     }
      //     return null;
      //   })
      //   .filter((item, i, self) => item && self.indexOf(item) === i);
      // Object.assign(this, {
      //   expandedKeys,
      //   searchValue: value,
      //   autoExpandParent: true,
      // });
    },
    handleClose () {
      this.loading = true
      this.typeShow = false
      this.getList()
    },
    handlePageChange (pageNo, pageSize) {
      this.loading = true
      this.pageNo = pageNo
      this.getList()
    },
    showSizeChange (pageNo, pageSize) {
      this.loading = true
      this.pageNo = 1
      this.pageSize = pageSize
      this.getList()
    },
    treeSelect (value) {
      const data=this.treeData.find(item=>item.id == value[0])
      if(data){
        this.treeId = null
        this.query.treeIdList= data.children.map(item=>item=item.id)
      }else{
        this.query.treeIdList=null
        this.treeId=value[0]
      }
      this.getList()
    },
    treeCheck (e) {
      console.log('check', e)
    },
      getTable(value) {
            this.queryParam.id = this.selectOptions.id
            this.queryParam.parentId = this.selectOptions.id
            this.$refs.table.refresh(true)
        },
    treeSearch (e) {
      this.getTree()
    },
    getTree () {
      this.treeShow = true
      this.loading = true
      
      queryComplaintTree({ name: this.searchValue }).then(res => {
        if (res.code == 200) {
          this.tree = res.data
          this.treeShow = false
          this.treeId = ''
          this.getList()
        } else {
          this.tree = res.data
          this.treeShow = false
        }
      }).catch(err => {
        this.loading = false
        this.treeShow = false
        this.tableData = []
      })
    },
    handleSubmit () {
      updateByPrimaryKeySelective(this.formData).then(res => {
        
        this.search()
        this.typeShow = false
      })
    },
    addCustList (e) {
      this.formData = e
      this.typeShow = true
    },
    search (val) {
      console.log(val,this.treeId)
      this.loading = true
      this.query = { ...val }
      this.$refs.table.refresh()
    },
    getList () {
      this.$refs.table.refresh()
    },
    changeCompletionDate (value, dateString) {
      this.formData.createTime = dateString
    },
    submit () {
      this.$refs.RuleForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.state == 1) {
            addCustomerDataManager(this.formData).then(res => {
              if (res.code == 200) {
                this.$message.success('提交成功')
                this.$router.push({ path: '/complaint/customerService/list' })
              }
            })
          } else if (this.state == 2) {
            editCustomerDataManager(this.formData).then(res => {
              if (res.code == 200) {
                this.$message.success('修改成功')
                this.$router.push({ path: '/complaint/customerService/list' })
              }
            })
          }
          this.loading = false
        }
      })

    }
  }
}
</script>
          <style lang="less" scoped>
/deep/.ant-modal {
  width: 500px !important;
}
/deep/.ant-form-item {
  display: flex;
}
</style>